define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "UtilDir/loading",
    "http://api.tianditu.gov.cn/api?v=4.0&tk=aeb17a8215786a5dd17f5f9c92bebc0c",
    "Date","DateCN", "css!DateCss",
    "EasyUI","EasyUI-lang"
],function(Util, Tool, SelectOrg, SearchBlock, Loading){

    var sysPath =  getServer() + "/static/app/cdqh/qhdatavisualquery";
    var qhDrillAttachmentFormHtml = sysPath + "/views/qhDrillAttachmentForm.html";

    var getQhDrillY02Controller = function(){
        return getServer() + "/qh/qhY02";
    };
    var getQhDrillY04Controller = function(){
        return getServer() + "/qh/qhY04";
    }
    var getQhDrillY05Controller = function(){
        return getServer() + "/qh/qhY05";
    };
    var getQhDrillY06Controller = function(){
        return getServer() + "/qh/qhY06";
    };
    var getQhDrillY08Controller = function(){
        return getServer() + "/qh/qhY08";
    };
    var getQhDrillY18Controller = function(){
        return getServer() + "/qh/qhY18";
    };

    /**
     * 页面初始化
     */
    var init = function(){
        var t = setInterval(function () {
            if (T.Control.OverviewMap && T.MarkerClusterer) {
                clearInterval(t);
                initSearchBlock();
                queryBtnBind();
                initcreateProvince();
                initMap();
                selectTab(0);
            }
        }, 10);
    };

    var initcreateProvince = function () {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer()+"/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    }
    var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
        require(["jquery", "Date", "DateCN", "css!DateCss"], function ($) {
            $("#constructionStartDateFrom").datetimepicker({
                //设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
                language: "cn",
                //输出格式化
                format: 'yyyy',
                //直接选择‘今天’
                todayBtn: true,
                weekStart: 1,
                // 设置最精确的时间选择视图
                startView: 4,
                //设置最精确的时间选择视图
                minView: 4,
//              minView: 'month',
                //高亮当天日期
                todayHighlight: true,
                //选择完毕后自动关闭
                autoclose: true
            });
            /* 删除按钮 */
            $("#complex_show1").on("click", function () {
                $('#constructionStartDateFrom').datetimepicker('show');
            });
            /* 显示按钮 */
            $("#complex_del1").on("click", function () {
                $("#constructionStartDateFrom").val("");
            });

            $("#constructionStartDateTo").datetimepicker({
                //设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
                language: "cn",
                //输出格式化
                format: 'yyyy',
                weekStart: 1,
                // 设置最精确的时间选择视图
                startView: 4,
                //直接选择‘今天’
                todayBtn: true,
                //设置最精确的时间选择视图
                minView: 4,
                //minView: 'month',
                //高亮当天日期
                todayHighlight: true,
                //选择完毕后自动关闭
                autoclose: true
            });
            /* 删除按钮 */
            $("#complex_show2").on("click", function () {
                $('#constructionStartDateTo').datetimepicker('show');
            });
            /* 显示按钮 */
            $("#complex_del2").on("click", function () {
                $("#constructionStartDateTo").val("");
            });
        })
    };
    var queryBtnBind = function(){
        $("#constructionStartDateFrom").change(function () {
            if ($("#constructionStartDateFrom").val() != "" && $("#constructionStartDateTo").val() != "") {
                if ($("#constructionStartDateFrom").val() > $("#constructionStartDateTo").val()) {
                    Util.alert("开始日期必须小于等于结束日期", function () {
                        $("#constructionStartDateFrom").val("");
                        $("#constructionStartDateTo").val("");
                    });
                    return;
                }
            }
        });
        $("#constructionStartDateTo").change(function () {
            if ($("#constructionStartDateFrom").val() != "" && $("#constructionStartDateTo").val() != "") {
                if ($("#constructionStartDateFrom").val() > $("#constructionStartDateTo").val()) {
                    Util.alert("开始日期必须小于等于结束日期", function () {
                        $("#constructionStartDateFrom").val("");
                        $("#constructionStartDateTo").val("");
                    });
                    return;
                }
            }
        });
        $("#btnSearch").click(function () {
            queryQhDrillData();
        });
        $("#btnReset").click(function () {
            $("#provinceSelect").val("");
            $("#citySelect").val("");
            $("#areaSelect").val("");
            $("#town").val("");
            $("#drillSynthesizeCode").val("");
            $("#siteClass").val("");
            $("#drillDepthFrom").val("");
            $("#drillDepthTo").val("");
            $("#constructionStartDateFrom").val("");
            $("#constructionStartDateTo").val("");
        });
        $("#searchButton").click(function () {
            if (isOpened) {
                rectTool.clear();
                rectTool.close();
                $("#searchButton").css("background-position", "61px 0");
                isOpened = false;
            } else {
                isOpened = true;
                $(this).css("background-position", "61px -52px");
                searchMarker();
            }
        });
        $(".qhDrillInfoTabTitle > ul > li").click(selectTab);
        $("#qhDrillInfoClose").click(function () {
            $('#qhDrillInfo').hide(200); $(this).hide();
        });
        $("#qhDrillAccessoryInfoClose").click(function () {
            $('#qhDrillAccessoryInfo').hide(200);
            $(".cs-upload").remove();
        });
    };

    var queryQhDrillY02ForGrid = function() {
        if (!global_drillId) return;
        $.ajax({
            url: getQhDrillY02Controller() + "/" + global_drillId,
            contentType: "application/json",
            type: "get",
            success: function (data) {
                console.log(data);
                data.order_number = 1;
                createQhDrillY02Grid(data ? [data] : [{}]);
            }
        });
    };
    var createQhDrillY02Grid = function(datas) {
        var columns = [[
            {
                field:'order_number',
                title:'序号',
                width:'4%',
                align:'center',
            },
            {field: "ck", width:'20%', checkbox: true},
            {
                field:'drillSynthesizeCode',
                title:'钻孔综合编号',
                width:'12%',
                align:'center',
            },
            {
                field:'drillDependProject',
                title:'钻孔依托的项目',
                width:'18%',
                align:'center',

            },
            {
                field:'projectCompleteInstitution',
                title:'项目完成单位',
                width:'18%',
                //sortable: true,
                align:'center',
            },
            {
                field:'projectCompleteDate',
                title:'项目完成时间',
                width:'10%',
                align:'center',
            },
            {
                field:'projectPrincipal',
                title:'项目负责人',
                width:'13%',
                align:'center',
            },
            {
                field:'drillConstructionInstitution',
                title:'钻孔勘察单位',
                width:'17%',
                align:'center',
            },
            {
                field:'drillConstructionPrincipal',
                title:'钻孔勘察负责人',
                width:'15%',
                align:'center',
            },
            {
                field:'constructionStartDate',
                title:'勘察施工日期',
                width:'15%',
                align:'center',
            },
            {
                field:'constructionReportDate',
                title:'勘察报告日期',
                width:'15%',
                align:'center',
            },{
                field:'drillCode',
                title:'钻孔编号',
                width:'13%',
                align:'center',
            },{
                field:'drillX',
                title:'孔口记录坐标X轴',
                width:'12%',
                align:'center',
            },{
                field:'drillY',
                title:'孔口记录坐标Y轴',
                width:'12%',
                align:'center',
            },{
                field:'longitude',
                title:'孔位经度（°）',
                width:'15%',
                align:'center',
            },
            {
                field:'latitude',
                title:'孔位纬度（°）',
                width:'15%',
                align:'center',
            },
            {
                field:'drillDepth',
                title:'钻孔深度（m）',
                width:'15%',
                align:'center',
            },
            {
                field:'elevation',
                title:'地面高程（m）',
                width:'15%',
                align:'center',
            },
            {
                field:'stableWaterDepth',
                title:'稳定水位深度（m）',
                width:'15%',
                align:'center',
            },
            {
                field:'coordinatesDeclare',
                title:'坐标系说明',
                width:'15%',
                align:'center',
            },
            {
                field:'elevationDeclare',
                title:'高程系说明',
                width:'15%',
                align:'center',
            },
            {
                field:'province',
                title:'钻孔所在省级行政区',
                width:'15%',
                align:'center',
            },
            {
                field:'city',
                title:'钻孔所在地市级行政区',
                width:'15%',
                align:'center',
            },
            {
                field:'area',
                title:'钻孔所在县级行政区',
                width:'15%',
                align:'center',
            },
            {
                field:'village',
                title:'钻孔所在乡级行政区',
                width:'15%',
                align:'center',
            },
            {
                field:'drillRemark',
                title:'钻孔说明备注',
                width:'15%',
                align:'center',
            },
            {
                field:'accessory',
                title:'附件',
                width:'15%',
                align:'center',
                formatter:function(value, rowData, rowIndex){
                    //console.log(value, rowData, rowIndex);
                    //return '<a href="javascript:void(0);" onclick="_editQhY02DrillAttachment(\'' + rowData.id + "','" + rowData.accessory +'\');">查看附件</a> '
                    return '<a href="javascript:void(0);" onclick="_showQhY02DrillAttachments(\'' + rowData.accessory +'\');">查看附件</a> '
                }
            },
        ]];
        $("#qhDrillY02Grid").datagrid({
            data: datas,
            method: "GET",
            //striped: true,
            nowrap: false,
            //rownumbers: true,
            fitColumns: true,
            autoRowHeight: false,
            idField: 'id',
            singleSelect: true,
            columns: columns,
            onBeforeLoad: function () {
                $(".qhDrillInfoContent").children().eq(0).find(".datagrid-pager.pagination").hide();
            },
            onLoadSuccess: function () {
                $(".qhDrillInfoContent").children().eq(0).find(".datagrid-view1").find(".datagrid-body").css("height", "190px");
                $(".qhDrillInfoContent").children().eq(0).find(".datagrid-view").css("height", "250px");
                $(".qhDrillInfoContent").children().eq(0).find(".datagrid-view2").find(".datagrid-body").css("height", "210px");
                $(".qhDrillInfoContent").children().eq(0).find(".datagrid-view2").find(".datagrid-header").find(".datagrid-header-inner").find(".datagrid-htable").find(".datagrid-header-check").css("width", "80px").html("").append("<div style='margin-left: 3px;'>单选成孔信息</div>");
                $(".qhDrillInfoContent").children().eq(0).find(".datagrid-view2").find(".datagrid-body").find(".datagrid-btable").find(".datagrid-cell-check").css("width", "80px");
                if (clickOrDraw == "click") {
                    $("#qhDrillY02Grid").datagrid("selectRow", 0);
                } else {
                    $("#qhDrillY02Grid").datagrid("unselectAll");
                }
            },
            onSelect: function (rowIndex, rowData) {
                console.log("rowData.id:", rowData.id);
                global_drillId = rowData.id;
            },
            onUnselect: function (rowIndex, rowData) {
                console.log("onUnselect");
                global_drillId = null;
            },
            pagination: true,
            pageSize: 10
        });
    };
    var createQhDrillY04Grid = function() {
        console.log("global_drillId:", global_drillId)
        var columns = [[
                //{field:"ck",checkbox:true},
                {
                    field:'assiseNumber',
                    title:'地层序号',
                    width:'10%',
                    align:'center',
                },
                {
                    field:'assiseCode',
                    title:'地层编号',
                    width:'10%',
                    align:'center',

                },
                {
                    field:'formationAge',
                    title:'地层年代',
                    width:'15%',
                    //sortable: true,
                    align:'center',
                },
                {
                    field:'causeAge',
                    title:'成因年代',
                    width:'10%',
                    align:'center',
                },
                {
                    field:'bottomDepth',
                    title:'层底深度（m）',
                    width:'10%',
                    align:'center',
                },
                {
                    field:'layerThickness',
                    title:'分层厚度（m）',
                    width:'10%',
                    align:'center',
                },
                {
                    field:'geotechnicalName',
                    title:'岩土名称',
                    width:'13%',
                    align:'center',
                },
                {
                    field:'geotechnicalCharacteristics',
                    title:'岩土特征',
                    width:'29%',
                    align:'center',
                },
            ]];
        if (!global_drillId) {
            $("#qhDrillY04Grid").datagrid({url: "", columns: columns, data: []});
            Util.alert("请选择一条Y02成孔信息，查看与此相关内容.");
            $("#system_dialog_alert").css("z-index", 100002);
            $(".modal-backdrop.fade.in").css("z-index", 100001);
            return;
        }
        $("#qhDrillY04Grid").datagrid({
            url: getQhDrillY04Controller() + "/queryQhY04s",
            method: "GET",
            fitColumns: true,
            nowrap: false,
            autoRowHeight: false,
            idField: 'id',
            columns: columns,
            queryParams:{
                drillId: global_drillId
            },
            pagination: true,
            pageSize: 10
        });
    };
    var createQhDrillY05Grid = function() {
        var columns = [[
                {
                    field:'standardStartDepth',
                    title:'起始标贯深度(m)',
                    width:'30%',
                    align:'center',
                },
                {
                    field:'standardEndDepth',
                    title:'结束标贯深度(m)',
                    width:'30%',
                    align:'center',

                },
                {
                    field:'standardNumber',
                    title:'标贯值',
                    width:'30%',
                    //sortable: true,
                    align:'center',
                },
            ]];
        if (!global_drillId) {
            $("#qhDrillY05Grid").datagrid({url: "", columns: columns, data: []});
            Util.alert("请选择一条Y02成孔信息，查看与此相关内容.");
            $("#system_dialog_alert").css("z-index", 100002);
            $(".modal-backdrop.fade.in").css("z-index", 100001);
            return;
        }
        $("#qhDrillY05Grid").datagrid({
            url: getQhDrillY05Controller() + "/queryQhY05s",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            idField: 'id',
            columns: columns,
            queryParams:{
                drillId: global_drillId
            },
            pagination: true,
            pageSize: 10
        });
    };
    var createQhDrillY06Grid = function() {
        var columns = [[
            {
                field:'code',
                title:'序号',
                width:'20%',
                sortable: true,
                align:'center',
            },
            {
                field:'geotechnicalDesignation',
                title:'岩土性名称',
                width:'20%',
                align:'center',

            },
            {
                field:'bottomDepth',
                title:'层底深度(m)',
                width:'20%',
                //sortable: true,
                align:'center',
            },
            {
                field:'layerThickness',
                title:'层厚(m)',
                width:'20%',
                align:'center',
            },
            {
                field:'shearWaveVelocity',
                title:'剪切波波速V(m/s)',
                width:'20%',
                align:'center',
            },
        ]];
        if (!global_drillId) {
            $("#qhDrillY06Grid").datagrid({url: "", columns: columns, data: []});
            Util.alert("请选择一条Y02成孔信息，查看与此相关内容.");
            $("#system_dialog_alert").css("z-index", 100002);
            $(".modal-backdrop.fade.in").css("z-index", 100001);
            return;
        }
        $("#qhDrillY06Grid").datagrid({
            url: getQhDrillY06Controller() + "/queryQhY06s",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            idField: 'id',
            columns: columns,
            queryParams:{
                drillId: global_drillId
            },
            pagination: true,
            pageSize: 10
        });
    };
    var createQhDrillY08Grid = function() {
        var columns = [[
            {
                field:'code',
                title:'序号',
                width:'10%',
                align:'center',
            },
            {
                field:'specimenCode',
                title:'样品编号',
                width:'10%',
                align:'center',

            },
            {
                field:'specimenStartDepth',
                title:'取样深度顶点(m)',
                width:'15%',
                //sortable: true,
                align:'center',
            },
            {
                field:'specimenEndDepth',
                title:'取样深度底点(m)',
                width:'15%',
                align:'center',
            },
            {
                field:'soilName',
                title:'土层名称',
                width:'10%',
                align:'center',
            },
            {
                field:'naturalDensity',
                title:'密度(kg/m3)',
                width:'10%',
                align:'center',
            },{
                field:'modulus_shear_strain_005',
                title:'模量比(G/Gmax)剪应变(γ)（10-4×0.05)',
                width:'25%',
                align:'center',
            },{
                field:'modulus_shear_strain_010',
                title:'模量比(G/Gmax)剪应变(γ)（10-4×0.10)',
                width:'25%',
                align:'center',
            },
            {
                field:'modulus_shear_strain_050',
                title:'模量比(G/Gmax)剪应变(γ)（10-4×0.50)',
                width:'25%',
                align:'center',
            },
            {
                field:'modulus_shear_strain_100',
                title:'模量比(G/Gmax)剪应变(γ)（10-4×1.00)',
                width:'25%',
                align:'center',
            },
            {
                field:'modulus_shear_strain_500',
                title:'模量比(G/Gmax)剪应变(γ)（10-4×5.00)',
                width:'25%',
                align:'center',
            },{
                field:'modulus_shear_strain_1000',
                title:'模量比(G/Gmax)剪应变(γ)（10-4×10.00)',
                width:'26%',
                align:'center',
            },
            {
                field:'modulus_shear_strain_5000',
                title:'模量比(G/Gmax)剪应变(γ)（10-4×50.00)',
                width:'26%',
                align:'center',
            },{
                field:'modulus_shear_strain_10000',
                title:'模量比(G/Gmax)剪应变(γ)（10-4×100.00)',
                width:'27%',
                align:'center',
            },
            {
                field:'damp_shear_strain_005',
                title:'阻尼比(λ)剪应变(γ)（10-4×0.05)',
                width:'24%',
                align:'center',
            },
            {
                field:'damp_shear_strain_010',
                title:'阻尼比(λ)剪应变(γ)（10-4×0.10)',
                width:'24%',
                align:'center',
            },
            {
                field:'damp_shear_strain_050',
                title:'阻尼比(λ)剪应变(γ)（10-4×0.05)',
                width:'24%',
                align:'center',
            },
            {
                field:'damp_shear_strain_100',
                title:'阻尼比(λ)剪应变(γ)（10-4×1.00)',
                width:'24%',
                align:'center',
            },
            {
                field:'damp_shear_strain_500',
                title:'阻尼比(λ)剪应变(γ)（10-4×5.00)',
                width:'24%',
                align:'center',
            },
            {
                field:'damp_shear_strain_1000',
                title:'阻尼比(λ)剪应变(γ)（10-4×10.00)',
                width:'24%',
                align:'center',
            },
            {
                field:'damp_shear_strain_5000',
                title:'阻尼比(λ)剪应变(γ)（10-4×50.00)',
                width:'24%',
                align:'center',
            },
            {
                field:'damp_shear_strain_10000',
                title:'阻尼比(λ)剪应变(γ)（10-4×100.00)',
                width:'24%',
                align:'center',
            },
        ]];
        if (!global_drillId) {
            $("#qhDrillY08Grid").datagrid({url: "", columns: columns, data: []});
            Util.alert("请选择一条Y02成孔信息，查看与此相关内容.");
            $("#system_dialog_alert").css("z-index", 100002);
            $(".modal-backdrop.fade.in").css("z-index", 100001);
            return;
        }
        $("#qhDrillY08Grid").datagrid({
            url: getQhDrillY08Controller() + "/queryQhY08s",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            idField: 'id',
            columns: columns,
            queryParams:{
                drillId: global_drillId
            },
            pagination: true,
            pageSize: 10
        });
    };
    var createQhDrillY18Grid = function() {
        var columns = [[
            {
                field:'siteType',
                title:'场地类型',
                width:'20%',
                align:'center',
            },
        ]];
        if (!global_drillId) {
            $("#qhDrillY18Grid").datagrid({url: "", columns: columns, data: []});
            Util.alert("请选择一条Y02成孔信息，查看与此相关内容.");
            $("#system_dialog_alert").css("z-index", 100002);
            $(".modal-backdrop.fade.in").css("z-index", 100001);
            return;
        }
        $("#qhDrillY18Grid").datagrid({
            url: getQhDrillY18Controller() + "/queryQhY18s",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            idField: 'id',
            columns: columns,
            queryParams:{
                drillId: global_drillId
            },
            pagination: true,
            pageSize: 10
        });
    };

    window._showQhY02DrillAttachments = function (accessory, e) {
        console.log(e);
        if (($(".cs-upload-toolbar").get(0))) return;
        $("#qhDrillAccessoryInfo").show();
        viewFileUpload(accessory);
        var t = setInterval(function() {
            if ($(".cs-upload-toolbar").get(0)) {
                clearInterval(t);
                $(".cs-upload-toolbar").hide();
                var len = accessory ? accessory.split(",").length : null;
                console.log("$$$$$$$$$$$$$$");
                if (len != null) {
                    var cut_tr = $(".cs-upload").find("table tr");
                    //console.log("cut_tr:", cut_tr);
                    for (let i = 0; i < len + 1; i++) {
                        cut_tr.eq(i).find("td").eq(2).remove();
                        cut_tr.eq(i).find("td").eq(2).remove();
                    }
                } else {
                    console.log("###############");
                    var cut_tr = $(".cs-upload").find("table tbody");
                    cut_tr.append("<tr><td colspan='4'>无附件信息</td></tr>")
                }
                var r = $("#qhDrillInfoClose").css("right"), b = $("#qhDrillInfoClose").css("bottom");
                //console.log(r, b, parseInt(b));
                var r_v = parseInt(r) + 70, b_v = parseInt(b) - 50;
                $("#qhDrillAccessoryInfo").css("right", r_v + "px");
                $("#qhDrillAccessoryInfo").css("bottom", b_v + "px");
            }
        }, 10);
    };

    var viewFileUpload = function (fileData) {
        require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
            var attachIdData = "";
            var attachId = "";
            var fileArray = "";
            if(fileData == null){
                fileData = "";
            }
            if (fileData.length != 0) {
                fileArray = fileData.split(',');
                attachIdData = fileData.split(',');
            }
            var settings = {
                placeAt: "multiFileUpload",
                allowMC: false,
                fileSizeLimit: 1024*1024*1024,
                allowDelete: false,
                /*
	            1.0.2版本新增
	            extendColumn:[
	                {name:"文件分类",filed:"category",format:function(file){return file.name}},
	                {name:"备注",filed:"remark",format:function(file){return '机密'}}
	            ],*/
                data: attachIdData
            };
            var MFUpload = MFU.init(settings);

        });
    };

    var tdMap, rectTool, infoWindow = new T.InfoWindow("", {offset: new T.Point(0, 0), minWidth: 300, minHeight: 170});
    var global_drillId, global_titleId, global_markerClusterer, global_markers = [], loading = Loading({text : "正在查询数据..."});
    var clickOrDraw, isOpened;
    var initMap = function () {
        var mapH = document.body.clientHeight - $(".pd-search-container").height() - 10;
        $("#qhDrillOverviewMap").height(mapH);

        var vec_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/d9ffc071-50dd-4780-a617-673d17921e22/wmts?service=wmts&request=gettile&version=1.0.0&layer=vec&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
        var cva_layer = new T.TileLayer("https://fxpc.mem.gov.cn/data_preparation/171dd1d5-bbb3-483a-a7f6-50d6d98cee1f/13f8b69d-98dc-4276-bbf0-9c4c372acabc/wmts?service=wmts&request=gettile&version=1.0.0&layer=cva&style=default&tilematrixset=c&format=tiles&tilematrix={z}&tilerow={y}&tilecol={x}&geokey=94E99EB4FEB9B48CD5348F7BCF5BB620");
        var config = {
            projection: 'EPSG:4326',
            minZoom: 4,
            layers: [vec_layer, cva_layer]
        };
        tdMap = new T.Map('qhDrillOverviewMap', config), zoom = 4;
        tdMap.centerAndZoom(new T.LngLat(106.34766, 34.37971), zoom);

        //var layers = tdMap.getLayers();
        //tdMap.removeLayer(layers[2]); tdMap.removeLayer(layers[3]);

        tdMap.addEventListener("click", function () {
            $('#queryDiv').hide();
        });

        var control=new T.Control.Zoom();
        tdMap.addControl(control);

        //创建比例尺控件对象
        var scale = new T.Control.Scale();
        tdMap.addControl(scale);

        //创建鹰眼控件对象
        var miniMap = new T.Control.OverviewMap({
            isOpen: true,
            size: new T.Point(150, 150)
        });
        tdMap.addControl(miniMap);

        //创建地图类型控件对象
        var ctrl = new T.Control.MapType();
        tdMap.addControl(ctrl);

        rectTool = new T.RectangleTool(tdMap);
        rectTool.addEventListener("draw", endRectDraw);
    };
    var searchMarker = function () {
        rectTool.clear();
        rectTool.open();
    };
    var endRectDraw = function (params) {
        clickOrDraw = "draw";
        global_drillId = null;
        selectTab(0);
        tdMap.clearOverLays();
        queryQhDrillData(params.currentBounds);
        $("#searchButton").css("background-position", "61px 0");
        isOpened = false;
    };
    var markerClick = function (e) {
        clickOrDraw = "click";
        $("#qhDrillInfo").show();
        //console.log(e);
        //console.log(e.lnglat.lng, e.lnglat.lat);
        var drill_id = e.target.options._data.id;
        global_drillId = drill_id;
        refreshQhDrillGrid(global_titleId);
        $("#qhDrillInfoClose").show();
    };

    var queryQhDrillData = function(bounds) {
        console.log("bounds: ", bounds);
        tdMap.clearOverLays();
        global_markerClusterer && global_markerClusterer.removeMarkers(global_markers); global_markers = [];
        var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "", town = $("#town").val() || "";
        var drillSynthesizeCode = $("#drillSynthesizeCode").val() || "", siteClass = $("#siteClass").val() || "";
        var drillDepthFrom = $("#drillDepthFrom").val() || "", drillDepthTo = $("#drillDepthTo").val() || "",
            cStartDateFrom = $("#constructionStartDateFrom").val() || "", cStartDateTo = $("#constructionStartDateTo").val() || "";
        var parameter_str = "province=" + province + "&city=" + city + "&area=" + area + "&village=" + town +
            "&drillSynthesizeCode=" + drillSynthesizeCode + "&siteType=" + siteClass +
            "&drillDepthBegin=" + drillDepthFrom + "&drillDepthEnd=" + drillDepthTo +
            "&constructionStartDateBegin=" + cStartDateFrom + "&constructionStartDateEnd=" + cStartDateTo;
        loading.show(); $(".cs-loading").css("z-index", 100001); $(".cs-loading-mask.fixed").css("z-index", 100000);
        $.ajax({
            url: getQhDrillY02Controller() + "/queryQhY02NoPage?" + parameter_str,
            contentType: "application/json",
            type: "get",
            success: function (data) {
                loading.close();
                if(bounds){
                    $("#qhDrillInfo").show(); $("#qhDrillInfoClose").show();
                } else {
                    $("#qhDrillInfo").hide(); $("#qhDrillInfoClose").hide();
                }
                console.log(data);
                if (data && data.data && data.data.length) {
                    var lnglat, points = [], fit_data = [], lon , lat; data = data.data, idx = 0;
                    for (let i = 0; i < data.length; i++) {
                        lon = parseFloat(data[i].longitude); lat = parseFloat(data[i].latitude);
                        //console.log(lon, lat);
                        if (lon > 180 || lat > 90 || lon < -180 || lat < -90 || isNaN(lon) || isNaN(lat)) continue;
                        lnglat = T.LngLat(lon, lat);
                        if (bounds && (!bounds.contains(lnglat))) continue;
                        var marker = new T.Marker(lnglat, {_data: data[i]});
                        //tdMap.addOverLay(marker);
                        marker.addEventListener("click", markerClick);
                        points.push(lnglat);
                        global_markers.push(marker);
                        data[i].order_number = (idx + 1);
                        fit_data.push(data[i]);
                        idx++;
                    }
                    tdMap.setViewport(points);
                    global_markerClusterer = new T.MarkerClusterer(tdMap, {markers: global_markers, girdSize: 80, styles: markerClustererStyles});
                    createQhDrillY02Grid(fit_data);
                } else {
                    createQhDrillY02Grid([{}]);
                    Util.alert("查询无数据!");
                }
            },
            error: function(xhr, state, errorThrown){
                loading.close();
                Util.alert("查询数据出现异常!");
            }
        });
    };

    var selectTab = function (idx) {
        //console.log(this, arguments);
        var aDiv = $('.qhDrillInfoTabTitle > ul > li'), _this = (idx == 0 ? $(aDiv.get(idx)) : $(this));
        console.log(_this.attr("id"));
        _this.removeClass('qhDrillInfoTabCurrent').siblings().addClass('qhDrillInfoTabCurrent');
        var index = _this.index();
        $('.qhDrillInfoContent > div').eq(index).show().siblings().hide();

        var titleId = _this.attr("id");
        global_titleId = titleId;
        refreshQhDrillGrid(titleId);

        if (idx == 0) {
            var mapWidth = $("#qhDrillOverviewMap").width(), factor = 0.75, infoWidth = mapWidth * factor;
            var lr_half = mapWidth * ((1 - factor) / 2);
            $("#qhDrillInfo").width(infoWidth).css("left", lr_half);

            var info_btn_close = $("#qhDrillInfo").height() + 30;
            $("#qhDrillInfoClose").css("right", lr_half + 15).css("bottom", info_btn_close);
        }
    };
    var refreshQhDrillGrid = function (titleId) {
        //titleId == "Y02" && (createQhDrillY02Grid());
        titleId == "Y02" && (clickOrDraw == "click") && (queryQhDrillY02ForGrid());
        titleId == "Y04" && (createQhDrillY04Grid());
        titleId == "Y05" && (createQhDrillY05Grid());
        titleId == "Y06" && (createQhDrillY06Grid());
        titleId == "Y08" && (createQhDrillY08Grid());
        titleId == "Y18" && (createQhDrillY18Grid());
    };

    var markerClustererStyles = [
        {
            url:'/qh/static/app/cdqh/images/cluster0.png',
            size:[53, 52], //图片大小
            //offset:new T.Point(-15, -13), //显示图片的偏移量
            textColor:'#000000', //显示数字的颜色
            //textSize:8,//显示文字的大小
            range:[0, 50],
        },
        {
            url:'/qh/static/app/cdqh/images/cluster1.png',
            size:[53, 52],
            //offset:new T.Point(-20, -17),
            textColor:'#000000',
            //textSize:10,
            range:[50, 200],
        },
        {
            url:'/qh/static/app/cdqh/images/cluster2.png',
            size:[53, 52],
            //soffset:new T.Point(-10, -22),
            textColor:'#000000',
            //textSize:12,
            range:[200, 500],
        },
        {
            url:'/qh/static/app/cdqh/images/cluster3.png',
            size:[53, 52],
            //soffset:new T.Point(-10, -22),
            textColor:'#000000',
            //textSize:12,
            range:[500, 1000],
        },
        {
            url:'/qh/static/app/cdqh/images/cluster4.png',
            size:[53, 52],
            //soffset:new T.Point(-10, -22),
            textColor:'#000000',
            //textSize:12,
            range:[1000, 10000],
        }
    ];


    return {
        init:init
    };
});
